/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package com.chinamobile.cmss.lakehouse.core.pipeline;

import com.chinamobile.cmss.lakehouse.common.dto.LakehouseCreateRequest;
import com.chinamobile.cmss.lakehouse.common.dto.LakehouseReleaseRequest;
import com.chinamobile.cmss.lakehouse.common.enums.ResourceSizeEnum;
import com.chinamobile.cmss.lakehouse.core.handler.K8sServiceHandler;
import com.chinamobile.cmss.lakehouse.core.queue.QueueResourceService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class QueueOpsHandler implements CreateHandler<ClusterCreateContext>,
    ReleaseHandler<ClusterReleaseContext>, CheckHandler<ClusterCheckContext> {

    @Autowired
    private QueueResourceService queueResourceService;

    @Override
    public boolean handleCreate(ClusterCreateContext context) {
        try {
            LakehouseCreateRequest request = context.getRequest();
            String instance = request.getInstance();
            String queueName = K8sServiceHandler.clusterNamespace(instance);
            ResourceSizeEnum resourcePoolSizeEnum = request.getResouceSize();
            return queueResourceService.createYunikornQueue(queueName, resourcePoolSizeEnum);
        } catch (Exception ex) {
            log.info("Cannot create queue: {}", ex.getMessage());
            return false;
        }
    }

    @Override
    public boolean handleRelease(ClusterReleaseContext context) {
        LakehouseReleaseRequest releaseRequest = context.getReleaseRequest();
        String instance = releaseRequest.getInstance();
        String queueName = K8sServiceHandler.clusterNamespace(instance);
        return queueResourceService.deleteYunikornQueue(queueName);
    }

    @Override
    public boolean handleCheck(ClusterCheckContext context) {
        String instance = context.getRequest().getInstance();
        String queueName = K8sServiceHandler.clusterNamespace(instance);
        return queueResourceService.checkExists(queueName);
    }
}
